<template>
  <div class='box-wrap2'>
    <section class='box-operation2' >
      <div class="box-num"> 
        <div class="box-selectnum">
           <el-select
                 @change="onChangedistric2()"
                 v-model="seg_code_from"
                 placeholder="号段展示"
                 :clearable="true"
                 size="mini"
                 filterable
                 multiple
                 :collapse-tags="collapse"
               >
                 <el-option
                   v-for="row in list.slice((currentpage2-1) * pageSize2, currentpage2 * pageSize2)"
                   :key="row.id"
                   :label="row.seg_code_from"
                   :value="row.id"
                   placeholder="请输入"
                 >
                 {{row.seg_code_from}}
                 </el-option>
                   <el-pagination
                     small
                     @current-change="handleCurrentChange2"
                     :current-page="currentpage2"
                     :page-size="pageSize"
                     layout="prev, pager,next,total"
                     :total="list.length"
                   >
                 </el-pagination>
           </el-select>              
        </div>
      </div>
    </section>
    <div class='form-group-addimg' @click='editInfo(1,{})'><img src="../../assets/images/peach-svg/sbmit.svg"></div>    
    <div class="box-wrap-lib-num">
      <div class="box-wrap-lib-chile">
        <div class="Table-up">
          <div class="Table-up-sele">
            <div class='form-group-enquire'>
                <el-select ref="select1" v-model="country_id" clearable placeholder="请输入国家" @change="initSearchData2()"  transfer filterable >
                    <el-option :value= index  :label= row.full_name v-for="(row,index) in Counlist" :key= index >{{row.short_name}}-{{row.full_name}}</el-option>
                </el-select>
            </div>
            <div class='form-group-enquire'>
                <el-select v-model="country_code " clearable placeholder="请输入城市查询" @change="onChangeKey2()" transfer filterable>
                    <el-option :value= index :label= "row.area_name=='all'?'搜索全部城市':row.area_name"   v-for="(row,index) in cityList" :key= index>{{row.area_name=="all"?"搜索全部城市":row.area_name}}</el-option>
                </el-select>
            </div>
            <div class='form-group-enquire'>
                  <el-select
                        @change="onChangeKeyEarth2()"
                        v-model="district_code"
                        placeholder="请选择地区编码"
                        :clearable="true"
                        size="mini"
                        filterable
                      >
                        <el-option
                          v-for="(item,index) in DistrictCodesList.slice((currentpage-1) * pageSize, currentpage * pageSize)"
                          :key="index"
                          :label="item.district_code=='all'?'搜索全部地区':item.district_code"
                          :value="index"
                          placeholder="请输入"
                        >
                        {{item.district_code=='all'?'搜索全部地区':item.district_code}}
                        </el-option>
                          <el-pagination
                            small
                            @current-change="handleCurrentChange"
                            :current-page="currentpage"
                            :page-size="pageSize"
                            layout="prev, pager,next,total"
                            :total="DistrictCodesList.length"
                          >
                        </el-pagination>
                   </el-select>          
            </div>    
            <div class='form-group-enquire'>
                <el-select
                    @change="onChangedistric2()"
                    v-model="seg_code_from"
                    placeholder="请输入号段"
                    :clearable="true"
                    size="mini"
                    filterable
                    multiple
                    :collapse-tags="true"
                  >
                    <el-option
                      v-for="row in list.slice((currentpage2-1) * pageSize2, currentpage2 * pageSize2)"
                      :key="row.id"
                      :label="row.seg_code_from"
                      :value="row.id"
                      placeholder="请输入"
                    >
                    {{row.seg_code_from}}
                    </el-option>
                      <el-pagination
                        small
                        @current-change="handleCurrentChange2"
                        :current-page="currentpage2"
                        :page-size="pageSize"
                        layout="prev, pager,next,total"
                        :total="list.length"
                      >
                    </el-pagination>
              </el-select>            
            </div>   
          </div>
        </div>
        <LibVxeTable class="staticData1" 
                    border="none"    
                    :stripe="stripe"    
                    :tableColumns="tableColumns" 
                    :tableData="fromList" :slotHeader="slotHeader"  
                    resizable>
        </LibVxeTable>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import bus from "../../commons/EventBus"

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    const validateName = (rule, value, callback) =>{
      if(value == ""){
        callback(new Error("任务名称不能为空"));
      }else if(value.length > 20 ){
        callback(new Error("任务名称长度不超过20"));
      }else {
        callback();
      }
    };
    return {     
      stripe:false,      
      collapse:false,    
      currentpage: 1, 
      pageSize: 500,  
      currentpage2: 1,   
      pageSize2: 500,       
      seg_code_from:'',
      district_code:'',
      country_code:"",      
      country_id:"",      
      area_name:"",      
      list:[],
      info:{},
      cityList:[],
      DistrictCodesList:[],
      Counlist:[],
      fromObj:{},
      fromList:[],
      max_count:10,
      tableColumns:[
        {
          title: "区域代码",
          field: "country_code",
          align: 'center',
        },
        {
          title: "地区生成",
          field: "district_name",
          align: 'center',
        },
        {
          title: "城市",
          field: "city_name",
          align: 'center',
        },
        {
          title: "地区代码",
          field: "district_code",
          align: 'center',
        },
        {
          title: "开始号段",
          field: "seg_code_from",
          align: 'center',
        },
        {
          title: "结束号段",
          field: "seg_code_to",
          align: 'center',
        },
        {
          title: "运营商名称",
          field: "operator",
          align: 'center',
        },
      ],
      format: {  
        name:{
          labelName: "任务名称",
          labelType: "text",      
          placeholder:"请输入任务名称"
        },
        num:{
          labelName: "已选中号段数量",
          labelType: "text",     
          placeholder:"请输入简称",
          labelDisabled:true          
        },
        radio:{
          labelName: "是否开启去重",
          labelType: "switch",               
        },
        elnumber:{
          labelName: "生成数据数量",
          labelType: "elnumber",   
          placeholder:"请输入号码位数",
          // max:0
        } 
      },
      ruleValidate: {
        name:[{ required: true,validator:validateName, trigger: "blur" }],
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {      
    async initView(isMounted){
      // this.getList();
      if(isMounted){
       this.initSearchData()
      }
    },
    async initSearchData(){
      this.Counlist=[]
      let Countries = await Request.post("exclude", "GetCountries");//国家
      if (Countries.code == 0) {
        Countries.data.list.forEach((item) => {
          this.Counlist.push(item)
        })          
      }                 
      this.$refs.select1.visible=true
    },
    async initSearchData2(){
      this.cityList=[]
      this.country_code="",
      this.district_code="",
      this.seg_code_from="",
      this.DistrictCodesList=[],
      this.list=[]
      let city = await this.RequestPost("queryCities_list",{"country_code":this.Counlist[this.country_id].short_name});//城市     
      if (city.code == 0 && city.data.list!=null) {
        city.data.list.forEach((item) => {
          this.cityList.push(item)
        })      
      }    
      this.cityList.unshift({"area_name":"all"})
    },      
    async onChangeKey2(){
      this.DistrictCodesList=[]
      this.district_code="",
      // this.seg_code_from="",
      this.list=[]
      let name = this.cityList[this.country_code].area_name
      let shortname = this.Counlist[this.country_id].short_name 
      let DistrictCodes = await this.RequestPost("queryDistrictCodes_list",{"country_code":shortname,"area_name":name});//城市   
      if (DistrictCodes.code == 0) {
        DistrictCodes.data.list.forEach((item,index) => {
          this.DistrictCodesList.push(item)
        })        
      } 
      this.DistrictCodesList.unshift({"district_code":"all"})         
    },    
    async onChangeKeyEarth2(){
      // this.seg_code_from=''
      let name = this.cityList[this.country_code].area_name
      let shortname = this.Counlist[this.country_id].short_name    
      let district = this.DistrictCodesList[this.district_code].district_code
      let res = await this.RequestPost("queryDistrictSegs_list",{"country_code":shortname,"area_name":name,"district_code":district});//地区代码     
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) 

        this.list = res.data.list;
        this.list.forEach(item => {
        this.$set(this.fromObj,item.id,item) 
        })
      }       
    },          
    async onChangedistric2(){      
      let len = this.seg_code_from.length
      this.fromList=[]
        this.seg_code_from.forEach(item=>{
          this.fromList.push(this.fromObj[item])
        })
      if (len >=10) {
        this.collapse=true
      }       
    },    
    //添加 编辑用户
    async editInfo(type,row) {
      let res =""
      if(this.seg_code_from.length==0){
            throw utils.showTip('请完善数据选择');
      }else{
        let seg=this.seg_code_from
          seg=seg.join("|")      
          res = await this.RequestPost("createTask_item",{'submit_type':1,"number_segment_ids":seg,})
          if(res.code==0){
            this.max_count =  res.data.max_count
            this.handleType=type;
            let title = "";
            let info = {};
            let num=this.seg_code_from.length
            if(this.handleType==1){
              title = "号码生成";
              info = {
                name:"",
                num:num,
                radio:"1",
                elnumber:1,
              };
            }
            this.formPopIndex=await utils.showFormPage(
              { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
              info,
              this.format,
              this.ruleValidate,
              this.updateInfo,
              this.onSelectChange,
            );
        }else{
          utils.shadowModel(
              { 
               "icon":require('../../assets/images/peach-svg/hongtan.svg'),
               "modalContent":res.data,
               "title":"提示"
              });
        }
      }
      
       
    },    
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      let seg=this.seg_code_from
          seg=seg.join("|")
      if (this.handleType==1) {
        actionName = 'createTask_item';
        tipText = '创建成功！';   
        postData = {
          "name":postData.name,
          "number_segment_ids":seg,
          "de_duplication_enable":postData.radio,
          "generation_number_count":postData.elnumber,
          "submit_type":"",
          };
      }
      this.max_count = this.max_count > 1000000?1000000:this.max_count
      if(info.elnumber>this.max_count){
        postData["generation_number_count"] =info.elnumber= this.max_count
        utils.shadowModel(
              { 
               "icon":require('../../assets/images/Frame 427318277.svg'),
               "modalContent":"可生成最大数量为"+this.max_count,
               "title":"提示"
              });
      }else if(info.elnumber<=0){
        postData["generation_number_count"] = info.elnumber = 1
        utils.shadowModel(
              { 
               "icon":require('../../assets/images/Frame 427318277.svg'),
               "modalContent":"可生成数量不正确",
               "title":"提示"
              });
      }else{
        let res = await this.RequestPost(actionName, postData);
        code = res.code;
        if (code == 0) {
          // this.format.elnumber.max = 1;
          let res2 = await Request.post("number/tasks", "queryTasks_list");
          bus.$emit("number",res2.data.list)
          this.country_id="",
          this.country_code="",
          this.district_code="",
          this.seg_code_from="",
          this.cityList=[],
          this.DistrictCodesList=[],
          this.list=[]
          bus.$emit('search','')  
          utils.hideFormPage(this.formPopIndex);
          await utils.sleepMs(1000);
          // this.onSearchGetList();
          utils.showTip(tipText);
        }
          // this.open()
      }
      utils.hideLoading();
    },       
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    // async open() {
    //   const h = this.$createElement;
    //   this.$msgbox({
    //     title: '提示',
    //     message: h('div', null, [
    //           h('span',
    //              {
    //               style: 'color: #060606' 
    //              }, 
    //                '“全球号码生成的号段均来自于网络！真实性未知，选择生成的数据执行筛任务前，建议小量尝试，避免所选择生成的号段开通率过低！“ '
    //            ),
    //         ],
    //       ),
    //     showCancelButton: false,
    //     confirmButtonText: '确定',
    //     beforeClose: (action, instance, done) => {
    //       if (action === 'confirm') {
    //         instance.confirmButtonLoading = true;
    //         instance.confirmButtonText = '执行中...';
    //         setTimeout(() => {
    //           done();
    //           setTimeout(() => {   
    //             this.country_id="",
    //             this.country_code="",
    //             this.district_code="",
    //             this.seg_code_from="",
    //             this.cityList=[],
    //             this.DistrictCodesList=[],
    //             this.list=[]
    //             bus.$emit('search','')        
    //             instance.confirmButtonLoading = false;
    //           }, 300);
    //         }, 1000);
    //       } else {
    //         console.log('4');
    //         done();
    //       }
    //     }
    //   }).then(action => {
    //     this.$message({
    //       type: 'info',
    //       message: 'action: ' + action
    //     });
    //   });
    // },      
    handleSizeChange(val) {
          this.pageSize=val;
    },
    handleCurrentChange(val) {
        this.currentpage=val;
    },
    handleSizeChange2(val) {
          this.pageSize2=val;
    },
    handleCurrentChange2(val) {
        this.currentpage2=val;
    },             
  },
};
</script>  